const fs = require('fs')
const express = require('express')
const students = require('./router/students')

const router = express.Router() // 创建路由容器

router.get('/', (req, res) => {
  res.render('login.html', {})
})

router.get('/register', (req, res) => {
  res.render('register.html', {})
})

router.post('/login', (req, res) => {
  students.login(req.body, (flag) => {
    if (flag) {
      res.redirect('/index.html')
    } else {
      res.send('用户不存在或者密码错误')
    }
  })
})

router.post('/register', (req, res) => {
  students.register(req.body, (flag) => {
    if (flag) {
      res.redirect('/')
    } else {
      res.send('注册失败')
    }
  })

})

router.get('/index.html', (req, res) => {
  students.find(students => {
    res.render('index.html', {
      students: students
    })
  })
})

router.get('/students/new', (req, res) => {
  res.render('new.html', {})
})

router.post('/students/new', (req, res) => {
  students.save(req.body)
  res.redirect('/index.html')
})

router.get('/students/edit', (req, res) => {
  students.getStudentById(req.query.id, student => {
    res.render('edit.html', {
      student: student
    })
  })
})

router.post('/students/edit', (req, res) => {
  students.update(req.body)
  res.redirect('/index.html')
})

router.get('/students/delete', (req, res) => {
  students.delete(req.query)
  res.redirect('/index.html')
})

module.exports = router